<template>
<div :class="[$style.container]" @keyup.enter="onConfirm">
<el-dialog title="链接分享" :visible.sync="actualVisible" width="480px">
  <el-form :model="form" :rules="rules" size="small" label-width="80px" label-position="left" ref="fm" v-if="visible">

    <div>
      <div :class="[$style.detailWrap]" v-if="row">
        <div class="mr-3 text-primary">{{url}}</div>
        <div class="text-secondary">提取码: {{row.accessCode || '无'}}</div>
        <div class="ml-3">
          <el-button type="primary" size="mini" :loading="submitting" @click="onSave">保存</el-button>
          <el-button size="mini" @click="onCopy">复制</el-button>
        </div>
      </div>
      <div :class="[$style.createWrap]" v-else>
        <div class="text-secondary"> <i class="el-icon-link"></i> <span>还没有创建分享链接</span></div>
        <div class="ml-3">
          <el-button type="primary" size="mini" :loading="submitting" @click="onCreate">创建链接</el-button>
        </div>
      </div>
      <el-divider></el-divider>
    </div>

    <el-form-item prop="perms" label="权限">
      <el-checkbox-group v-model="form.perms">
        <el-checkbox label="allowPreview">允许预览</el-checkbox>
        <el-checkbox label="allowDownload">允许下载</el-checkbox>
        <el-checkbox label="allowEdit">允许编辑</el-checkbox>
        <!-- <el-checkbox label="allowUpload" disabled>允许上传</el-checkbox> -->
      </el-checkbox-group>
    </el-form-item>
    <el-form-item prop="accessCode" label="提取码">
      <el-switch v-model="form.useAccessCode" class="mr-4"></el-switch>
      <el-input v-model="form.accessCode" maxlength="4" style="width: 80px;" v-if="form.useAccessCode"></el-input>
    </el-form-item>
    <el-form-item prop="expiredTime" label="有效期">
      <el-switch v-model="form.useExpiredTime" class="mr-4"></el-switch>
      <el-date-picker v-model="form.expiredTime" type="date" value-format="yyyy/MM/dd" format="yyyy/MM/dd" placeholder="选择日期" v-if="form.useExpiredTime"></el-date-picker>
    </el-form-item>
    <el-form-item prop="auth" label="需要登录">
      <el-switch v-model="form.auth" class="mr-4"></el-switch>
    </el-form-item>
    <el-form-item prop="remark" label="说明">
      <el-input v-model="form.remark" :rows="2" placeholder="请添加链接说明" maxlength="30"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer">
    <!-- <el-button size="small" @click="onCancel" class="px-5" :disabled="submitting">取 消</el-button>
    <el-button size="small" type="primary" @click="onConfirm" :loading="submitting" class="px-5">确 定</el-button> -->
  </span>
</el-dialog>
</div>
</template>

<script lang="ts">

import { Vue, Component, Prop, Emit, Ref } from 'vue-property-decorator'
import { ModalMixins } from '@/mixins'
import { mixins } from 'vue-class-component'
import { textValidator } from '@/config/validator'
import { copyToClipboard } from '@/utils/copy'
import { randomString } from '@/utils/random'
import { createDocLink, updateDocLink } from '@/api/doc-link'
import { getInitOptions } from '@/config/init'

const keys = ['allowPreview', 'allowDownload', 'allowUpload', 'allowEdit']
function toPerms (row: any): string[] {
  if (!row) return []
  const ret: any[] = []
  keys.forEach(v => {
    if (row && row[v]) ret.push(v)
  })
  return ret
}

function fromPerm (perms: string[]): any {
  const ret: any = {}
  keys.forEach(v => {
    ret[v] = perms.includes(v)
  })
  return ret
}

@Component
export default class DocLinkEditModal extends mixins(ModalMixins) {
  @Ref() fm!: any

  data: any = null

  row: any = null

  form: any = null

  get rules () {
    return {
      name: [
        { required: true, message: '请输入名称' },
        { validator: textValidator }
      ]
    }
  }

  get url () {
    return getInitOptions().api + '/s/' + this.row.id
  }

  get isEdit () {
    return !!this.row
  }

  onCopy () {
    const sys = '[玖钉文档]'
    const name = this.row?.doc?.name || this.row?.name
    copyToClipboard(`${this.url} ${sys} ${name}`)
    this.$message.info('已复制到粘贴板')
  }

  open (data?: any, row?: any) {
    this.data = data || null
    this.row = row || null
    this.initForm()
    // this.$nextTick(() => {
    //   if (this.fm) this.fm.resetFields()
    // })
    return this.init()
  }

  initForm () {
    const row = this.row
    this.form = {
      perms: row ? toPerms(row) : [],
      useAccessCode: row ? (!!row?.accessCode) : true,
      accessCode: row ? (row?.accessCode || '') : randomString(4),
      useExpiredTime: row ? (!!row?.expiredTime) : false,
      expiredTime: row ? (row?.expiredTime || null) : null,
      remark: row ? (row.remark || '') : '',
      auth: !!row?.auth
    }
  }

  onCreate () {
    this.submit()
  }

  onSave () {
    this.submit()
  }

  submit () {
    const req = {
      ...fromPerm(this.form.perms),
      accessCode: this.form.useAccessCode ? this.form.accessCode : '',
      expiredTime: (this.form.useExpiredTime && this.form.expiredTime) ? (this.form.expiredTime + ' 23:59:59') : null,
      remark: this.form.remark,
      auth: this.form.auth,
      ...(this.isEdit ? {} : { docId: this.data?.id })
    }

    this.submitting = true
    const request = this.isEdit ? updateDocLink(this.row.id, req) : createDocLink(req)
    request.then(data => {
      this.row = data || null
      this.initForm()
    }).finally(() => {
      this.submitting = false
    })
  }

  onCancel () {
    this.cancel()
  }

  onConfirm () {
    // this.fm.validate().then((valid: boolean) => {
    //   if (!valid) return
    //   this.submitting = true
    //   const req = Object.assign({}, this.form)
    //   createDeptByParent(this.data?.id, req).then((data) => {
    //     this.complete(data)
    //   }).finally(() => {
    //     this.submitting = false
    //   })
    // })
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.detailWrap {
  display: flex;
  align-items: center;

  & > div:first-child {
    flex:  1 1 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  & > div:nth-child(2) {
    flex: 0 0 auto;
  }

  & > div:last-child {
    flex: 0 0 auto;
  }
}

.createWrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.text {
  font-size: 12px;
  margin-right: 8px;
  color: $text-secondary-color;
}

</style>
